package Store

import (
	"encoding/json"
	"fmt"
	"db2s/ref"
)

func getMetaCurryAutoIncrementValue(tabId int) (res uint64, err error) {
	var resMap map[string]string
	var auto AutoIncrement
	var insertKey = "auto"
	if resMap, err = Query(AutoIncrementMeta, "all"); err != nil {
		return
	}
	if k, ok := resMap[insertKey]; ok {
		if err = json.Unmarshal([]byte(k), &auto); err != nil {
			return
		}
		return
	}
	switch tabId {
	case TablesMeta:
		auto.Tables++
		res = auto.Tables
	default:
		return
		//panic("unhandled default case")
	}
	if err = Storage.Insert(getTableTypeStr(AutoIncrementMeta), map[string]string{insertKey: ref.AnyToJsonString(auto)}); err != nil {
		fmt.Println("--------err:", err)
		return
	}
	return
}

func getInputDataType(data any)(key string,id tableTypeId){
	switch data.(type) {
	case TablesData:
		var pp = data.(TablesData)
		return fmt.Sprintf("%v_%v_%v_%v_%v_%v", pp.Schema, pp.Table, pp.MSchema,pp.MTable, pp.Role, pp.TaskName),TablesMeta
	case MissTableData:
		var pp = data.(MissTableData)
		return fmt.Sprintf("%v_%v_%v_%v_%v_%v", pp.Schema, pp.Table, pp.MSchema,pp.MTable, pp.Role, pp.TaskName),MissTableMeta
	default:
		return
	}
}
func updateTableWriteAutoIncrement(data any) (newData any,err error){
	_,tableId := getInputDataType(data)
	switch data.(type) {
	case TablesData:
		var pp = data.(TablesData)
		if pp.Id, err = getMetaCurryAutoIncrementValue(int(tableId)); err != nil {
			return
		}
		newData = pp
	case MissTableData:
		var pp = data.(MissTableData)
		if pp.Id, err = getMetaCurryAutoIncrementValue(int(tableId)); err != nil {
			return
		}
		newData = pp
	}
	return
}
func TableWriteData(data any) (err error){
	var newData any
	key,tableId := getInputDataType(data)
	if newData, err = updateTableWriteAutoIncrement(data); err != nil {
		return err
	}
	if err = Storage.Insert(getTableTypeStr(tableId), map[string]string{key: ref.AnyToJsonString(newData)}); err != nil {
		return
	}
	return
}
func TablesDataWrite(data TablesData) (err error) {

	return
}
func TableDataRead(key string) (TablesData any, err error) {
	return
}

func MissDataWrite() (){
	 return
}